#include<stdio.h>
#include<stdlib.h>
#include "linkqueue.h"

//创建队列
linkqueue * queue_create(){
	linkqueue * lq;
	if((lq = (linkqueue *)malloc(sizeof(linkqueue))) == NULL){
		printf("init queue is failed \n");
		return NULL;
	}
	linklist p;
	if((p = (linklist)malloc(sizeof(listnode))) == NULL){
		printf("init listnode failed \n");
		return NULL;
	}
	p->data = NULL;
	p->next = NULL;

	lq->front = lq->rear = p;
	return lq;
}
//入队
int enqueue(linkqueue *lq, datatype value){
	if(lq == NULL){
		printf("lq is NULL\n");
		return -1;
	}
	//新增节点
	linklist p;
	if((p = (linklist)malloc(sizeof(listnode))) == NULL){
		printf("init listnode failed \n");
		return -1;
	}
	p->data = value;
	p->next = NULL;
	//放到队尾
	lq->rear->next = p;
	//移动rear指针
	lq->rear = lq->rear->next;
	return 0;
}
//出队
datatype dequeue(linkqueue *lq){
	if(lq == NULL){
		printf("lq is NULL\n");
		return NULL;
	}
	//判断队列是否为空
	if(lq->front == lq->rear){
		printf("queue is empty\n");
		return NULL;
	}
	linklist p;
	p = lq->front;
	lq->front = lq->front->next;
	free(p);
	p = NULL;
	return lq->front->data;
}
//队列是否为空
int queue_empty(linkqueue *lq){
	if(lq == NULL){
		printf("lq is NULL\n");
		return -1;
	}
	return lq->front == lq->rear ? 1 : 0;
}
//清空队列
int queue_clear(linkqueue *lq){	
	linklist p;
	if(lq == NULL){
		printf("lq is NULL\n");
		return -1;
	}
	while(lq->front->next != NULL){
		p = lq->front;
		lq->front = lq->front->next;
		free(p);
		p = NULL;
	}
	return 0;
}
//释放队列空间
linkqueue * queue_free(linkqueue *lq){
	linklist p;
	if(lq == NULL){
		printf("lq is NULL\n");
		return NULL;
	}
	//释放节点
	while(lq->front != NULL){
		p = lq->front;
		lq->front = lq->front->next;
		//printf("free %d \n",p->data);
		free(p);
	}

	//释放链式队列 头节点 尾节点
	free(lq);
	lq = NULL;
	return NULL; 
}
